<?php

namespace App\Http\Model;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use phpDocumentor\Reflection\Types\Self_;

class UnionUser extends Base
{
    protected $user_table = "union_user";//公会成员表
    protected $table_union_user_rate = 'union_user_rate';//公会成员费率配置表

    protected $union_table = "union";
    protected $apply_user_table = "union_user_apply";
    protected $assign_user_role_table = "union_assign_user_role";
    protected $union_uuid_key = "UNION:UID:GENERATED:DB";
    protected $kick_user_to_union_key = "UNION:USER:KICK";
    protected $role_value = ['1' => 1, '2' => 2, '3' => 4, '4' => 8, '5' => 16, '6' => 32, '7' => 64, '8' => 128];
    protected $redis_union_role = 'UNION:ROLE';
    protected $redis_union_user_role = 'UNION:USER:ROLE:';
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->user_table, $attributes);
    }

    //添加公会成员
    public function createUnionUser($data)
    {
        return DB::table($this->user_table)->insertGetId($data);
    }


    /* 用户公会
     * $user_id 用户id
     * $rule 3 公会状态   0 未激活  1激活 3忽略
     * */
    public function userToUnion($user_id, $rule = 1)
    {
        $where['union.stop'] = 1;
//        if ($rule != 3) {
//            $where['union.rule'] = $rule;
//        }
        $where['user_id'] = $user_id;
//        $res = DB::table($this->user_table)->where($where)
//            ->leftJoin("union", "union.id", "=", "union_user.un_id")
//            ->select('union_user.*','portrait', 'union.id as union_id', 'union.un_user_id', 'union.rule', 'union.stop as union_stop', 'union.id as union_id',
//                'union.settle_type',
//                'union.name as union_name','liang', 'uuid', 'role_id','declaration','vest','deposit','authentication_status')
//            ->first();
        $res = DB::table($this->user_table)->where($where)
            ->leftJoin("union", "union.id", "=", "union_user.un_id")
//            ->leftJoin("room_role", "room_role.user_id", "=", "union_user.user_id")
            ->select('union_user.*','portrait', 'union.id as union_id', 'union.un_user_id', 'union.rule', 'union.stop as union_stop', 'union.id as union_id',
                'union.settle_type',
                'union.name as union_name','liang', 'uuid', 'role_id','declaration','vest','deposit','authentication_status')
            ->first();
        $res = $this->objToArray($res);
        $restype= DB::table('room_role')->where('user_id',$user_id)->first();
        $restype = $this->objToArray($restype);
        if ($res) {
            $res['portrait'] = build_image($res['portrait']);
            $res['role_type'] = $restype['role_type'];
        }
        return $this->objToArray($res);
    }

    //验证用户是否被踢120h以内
    public function checkUserDelTime($user_id)
    {
        $key = $this->kick_user_to_union_key . $user_id;
        return Redis::get($key);
    }

    //踢出用户
    public function kickUser($user_id)
    {
        $key = $this->kick_user_to_union_key . $user_id;
        return Redis::SETEX($key, 432000, time());
    }


    /*
     * 用户申请记录
     * */
    public function applyUserLog($user_id, $union_id = '')
    {
        $where['user_id'] = $user_id;
        if ($union_id) $where['un_id'] = $union_id;
        $res = DB::table($this->apply_user_table)->where($where)->orderBy('id','desc')->get();
        return $this->objToArray($res);
    }


    /* 用户公会
     * $user_id 用户id
     * $union_id  公会id
     * */
    public function applyUnionToUser($user_id, $union_id)
    {
        $data['user_id'] = $user_id;
        $data['un_id'] = $union_id;
        return DB::table($this->apply_user_table)->insertGetId($data);
    }

    /* 删除用户公会
     * $user_id 用户id
     * $union_id  公会id
     * */
    public function delApplyLogToUser($user_id)
    {
        $where['user_id'] = $user_id;
        return DB::table($this->apply_user_table)->where($where)->delete();
    }

    /*  删除已审核成功用户
       * $user_id 用户id
       * $union_id  公会id
       * */
    public function delApplyLogToStatus($user_id)
    {
        $where['user_id'] = $user_id;
        $where['status'] = 0;
        return DB::table($this->apply_user_table)->where($where)->delete();
    }
    /* 更新公会用户审核状态
     * $user_id 用户id
     * $union_id  公会id
     * */
    public function updateApplyLogToUser($user_id,$apply_user_id,$status,$union_id)
    {
        $where['user_id'] = $apply_user_id;
        $where['un_id'] = $union_id;
        $update['status'] = $status;//更改用户状态 0已申请 1审核通过  2拒绝
        $update['check_user_id'] = $user_id;//更新用户审核人id
        return DB::table($this->apply_user_table)->where($where)->update($update);
    }
    /*
     * 获取公会成员
     * $union_id  公会id
     * */
    public function getUnionUserList($union_id, $search)
    {
        $where['un_id'] = $union_id;
        $where[] = ['role_id', '>', '0'];
        $whereOr = $where;

        if ($search) {
            $where[] = ['uuid', 'like', "%$search%"];
            $whereOr[] = ['nickname', 'like', "%$search%"];
        }
        $role_user = DB::table($this->user_table)
            ->where($where)
            ->orWhere($whereOr)
            ->leftJoin("user", $this->user_table . ".user_id", "=", "user.user_id")
            ->orderBy('role_id', 'asc')
            ->select('portrait', 'user.user_id', 'role_id', 'un_id', 'uuid', 'gender', 'nickname', $this->user_table . '.created_at')
            ->get();
        $res['role_user'] = $this->objToArray($role_user);
        $role = $this->getRolesList();
        foreach ($res['role_user'] as &$v) {
            $v['portrait'] = build_image(json_decode($v['portrait'])[0]);
            $v['role_name'] =  isset($role[$v['role_id']]) ? $role[$v['role_id']] : '';
        }
        $whereUser['un_id'] = $union_id;
        $whereUser[] = ['role_id', '=', '0'];

        $whereUserOr = $whereUser;
        if ($search) {
            $whereUser[] = ['uuid', 'like', "%$search%"];
            $whereUserOr[] = ['nickname', 'like', "%$search%"];
        }
        $user = DB::table($this->user_table)
              ->where($whereUser)
              ->orWhere($whereUserOr)
              ->leftJoin("user", $this->user_table . ".user_id", "=", "user.user_id")
              ->orderBy('role_id', 'asc')
              ->select('portrait', 'user.user_id', 'role_id', 'un_id', 'uuid', 'gender', 'nickname', $this->user_table . '.created_at')
              ->get();
        $res['user'] = $this->objToArray($user);
        foreach ($res['user'] as &$vv) {
            $vv['portrait'] = build_image(json_decode($vv['portrait'])[0]);
            $vv['role_name'] =  isset($role[$vv['role_id']]) ? $role[$vv['role_id']] : '';
        }
        return $res;
    }

    public function getUnionUserListV2($union_id, $search, $page, $limit)
    {
        $where['un_id'] = $union_id;
        $whereOr = $where;
        if ($search) {
            $where[] = ['uuid', 'like', "%$search%"];
            $whereOr[] = ['nickname', 'like', "%$search%"];
            $user = DB::table($this->user_table)
                ->where($where)
                ->orWhere($whereOr)
                ->leftJoin("user", $this->user_table . ".user_id", "=", "user.user_id")
                ->orderBy('role_id', 'desc')
                ->select('portrait', 'user.user_id', 'role_id', 'un_id', 'uuid', 'gender', 'nickname', $this->user_table . '.created_at')
                ->offset($page * $limit)
                ->limit($limit)
                ->get();
        }else{
            if($page==0){
                $role_user = DB::table($this->user_table)
                    ->where($where)
                    ->where('role_id', '=', '1')
                    ->orderBy('role_id', 'asc')
                    ->leftJoin("user", $this->user_table . ".user_id", "=", "user.user_id")
                    ->select('portrait', 'user.user_id', 'role_id', 'un_id', 'uuid', 'gender', 'nickname', $this->user_table . '.created_at')
                    ->get();
                $res['role_user'] = $this->objToArray($role_user);
                $role = $this->getRolesList();
                foreach ($res['role_user'] as &$v) {
                    $v['portrait'] = build_image(json_decode($v['portrait'])[0]);
                    $v['role_name'] =  isset($role[$v['role_id']]) ? $role[$v['role_id']] : '';
                }
            }
            $where[] = ['role_id', '!=', '1'];
            $whereOr=$where;
            $user = DB::table($this->user_table)
                ->where($where)
                ->orWhere($whereOr)
                ->leftJoin("user", $this->user_table . ".user_id", "=", "user.user_id")
                ->orderBy('role_id', 'desc')
                ->select('portrait', 'user.user_id', 'role_id', 'un_id', 'uuid', 'gender', 'nickname', $this->user_table . '.created_at')
                ->offset($page * $limit)
                ->limit($limit)
                ->get();
        }

        $res['user'] = $this->objToArray($user);
        foreach ($res['user'] as &$vv) {
            $vv['portrait'] = build_image(json_decode($vv['portrait'])[0]);
//            $vv['role_name'] =  isset($role[$vv['role_id']]) ? $role[$vv['role_id']] : '';
        }
        $result = array_merge($res['user'], $res['role_user']);
        return $res;
    }
    /*
   * 成员退出公会
   * $user_id  用户id
   * $union_id  公会id
   * */
    public function quitUserUnion($union_id, $user_id = '')
    {
        $where['un_id'] = $union_id;
        if ($user_id) {
            $where['user_id'] = $user_id;
        }
        //删除对私配置
        DB::table($this->table_union_user_rate)->where($where)->delete();
        return DB::table($this->user_table)->where($where)->delete();
    }


    /*
     * 验证用户是否具有该权限 $this->role_value
     *  $role_rank   权限等级
     * 入会审批 1       1
     * 踢出公会 2       2
     * 任命职位 4       3
     * 公会头像 8       4
     * 公会昵称 16      5
     * 取消职位 32      6
     * 任命房间 64      7
     * 查看流水 128     8
     * $unino_id   公会id
     * */
    public function checkUserRole($user_id, $role_rank, $unino_id)
    {

        //查询用户当前权限值
        $where['user_id'] = $user_id;
        $where['un_id'] = $unino_id;
        $res = DB::table($this->user_table)->where($where)
            ->leftJoin("union_role", "union_role.id", "=", "union_user.role_id")
            ->first();
        $res = $this->objToArray($res);
        if (!$res) {
            return 0;
        }
        $user_role_value = $res['value']; // 用户权限值
        $role_rank_value = $this->role_value[$role_rank];//操作权限值
        return $user_role_value & $role_rank_value;
    }

    //用户职务数据
    public function userRole($user_id, $union_id)
    {
        $where['user_id'] = $user_id;
        $where['un_id'] = $union_id;
        $res = DB::table($this->user_table)->where($where)
            ->leftJoin("union_role", "union_role.id", "=", "union_user.role_id")
            ->first();
        return $this->objToArray($res);
    }

    //公会职务对应人数
    public function unionRoleCountNum($union_id)
    {
        $where['un_id'] = $union_id;
        $res = DB::table($this->user_table)->where($where)
            ->leftJoin("union_role", "union_role.id", "=", "union_user.role_id")
            ->selectRaw('role_id, count(zb_union_user.id) as count_role,upper')
            ->groupBy('role_id')
            ->get();
        return $this->objToArray($res);
    }

    public function getRoleInfo($role_id)
    {
        $where['id'] = $role_id;
        $res = DB::table('union_role')->where($where)->first();
        return $this->objToArray($res);
    }

    //生成任命记录
    public function addAssginUnionRoleLog($union_id, $user_id, $role_id)
    {
        $data['un_id'] = $union_id;
        $data['user_id'] = $user_id;
        $data['role_id'] = $role_id;
        return DB::table($this->assign_user_role_table)->insertGetId($data);
    }

    public function addUnionRoleLog($union_id, $user_id, $role_id)
    {
        $data['un_id'] = $union_id;
        $data['user_id'] = $user_id;
        $data['role_id'] = $role_id;
        return DB::table('union_user')->insertGetId($data);
    }
    //查询用户任命角色
    public function getAssginUnionRoleLog($union_id, $user_id, $role_id)
    {
        $where['un_id'] = $union_id;
        $where['user_id'] = $user_id;
        $where['role_id'] = $role_id;
        $res = DB::table($this->assign_user_role_table)->where($where)->first();
        return $this->objToArray($res);
    }

    //删除任命记录
    public function delAssignUnionRoleLogByUserId($union_id, $user_id)
    {
        $where['un_id'] = $union_id;
        $where['user_id'] = $user_id;
        return DB::table($this->assign_user_role_table)->where($where)->delete();
    }

    //删除任命记录
    public function delAssignUnionRoleLogById($id)
    {
        $where['id'] = $id;
        return DB::table($this->assign_user_role_table)->where($where)->delete();
    }

    //修改公会用户角色
    public function editUnionUserRole($union_id, $user_id, $role_id)
    {
        $where['un_id'] = $union_id;
        $where['user_id'] = $user_id;
        $data['role_id'] = $role_id;
        return DB::table($this->user_table)->where($where)->update($data);
    }

    /**获取公会角色列表
     * @return array
     */
    public function getRolesList()
    {
        $data = Redis::get($this->redis_union_role);
        if(!empty($data)){
            return json_decode($data ,true);
        }
        $res = DB::table('union_role')->orderBy('id','asc')->get(['id','name']);
        $res = $this->objToArray($res);
        $data = array();
        foreach ($res as $r){
            $data[$r['id']] = $r['name'];
        }
        if(!empty($data)){
            Redis::set($this->redis_union_role,json_encode($data));
        }
        return $data;
    }

    /**获取公会所有成员
     * @param $union_id
     * @param bool $num
     * @return \Illuminate\Support\Collection|int|mixed
     */
    public function getUserNum($union_id,$num=true){
        $res = DB::table($this->user_table)
            ->where('un_id' ,$union_id)
            ->orderBy('created_at','desc')
            ->get();
        $res = $this->objToArray($res);
        if($num){
            return count($res);
        }
        return $res;
    }

    /**根据user_ids获取公会id和角色
     * @param $user_ids
     * @return \Illuminate\Support\Collection|mixed
     */
    public function getUnionByUser($user_ids)
    {
        $res = DB::table($this->user_table)
            ->whereIn('user_id', $user_ids)
            ->orderBy('created_at', 'desc')
            ->get(['user_id', 'un_id', 'role_id']);
        $res = $this->objToArray($res);
        return $res;
    }
    /**
     * 获取公会下成员ID
     * @param int $union_id 公会Id
     * @return array
     */
    public function getUserIdsByUnionId($union_id)
    {
        $result = DB::table($this->user_table)->where(['un_id' => $union_id])->get(['user_id']);
        if (empty($result)) {
            return [];
        }

        return $this->objToArray($result);
    }

    public function isUnionUser($union_id, $uid){
        $res = DB::table($this->user_table)
            ->where('user_id',$uid)
            ->where('un_id', $union_id)
            ->first();
        return !empty($res);
    }

    /**根据公会id 和用户id 获取role信息
     * @param $user_ids
     * @return \Illuminate\Support\Collection|mixed
     */
    public function getUnionRoleById($union_id, $user_id) {
        $res = DB::table($this->table)
            ->where('un_id', $union_id)
            ->where('user_id', $user_id)
            ->leftJoin('union_role', $this->table . ".role_id", "=", "union_role.id")
            ->first();
        return [$res->role_id, $res->name];
    }

    /**
     * 判断用户中是否存在主播
     */
    public function checkUnionUserByUserIds($userIds) {
        //是否有主播
        $unionUser = 0;
        //获取用户公会
        $userUnionList = DB::table($this->user_table)
            ->whereIn('user_id', $userIds)
            ->orderBy('created_at', 'desc')
            ->get(['user_id', 'un_id', 'role_id']);
        $userUnionList = $this->objToArray($userUnionList);
        //公会是否认证
        if(!empty($userUnionList)) {
            foreach($userUnionList as $val) {
                $unionInfo = DB::table($this->union_table)->where('stop', 1)->where('id', $val['un_id'])->first();
                $unionInfo = $this->objToArray($unionInfo);
                if(!empty($unionInfo) && $unionInfo['authentication_status']>0) {
                    $unionUser = 1;
                    break;
                }
            }
        }

        return $unionUser;
    }

    /**
     * 根据用户ID获取对应公会信息
     */
    public function getUnionInfoByUserId($userId) {
        $unionInfo = DB::table($this->union_table)->where('un_user_id', $userId)->first();
        $unionInfo = $this->objToArray($unionInfo);

        return $unionInfo;
    }

    /**
     * 获取公会成员下配置的费率
     *
     * @param $unid 公会id
     * @param $userid 公会成员id
     * @param $confirmstatus false不查状态,true查询确认状态
     * @return array
     */
    public function getUnionUserRate($unid,$userid,$confirmstatus=true)
    {
        if($confirmstatus)
        {
            $where = ['un_id'=>$unid,'user_id'=>$userid,'confirm_status'=>1];
        }else{
            $where = ['un_id'=>$unid,'user_id'=>$userid];
        }
        $res = DB::table($this->table_union_user_rate)->where($where)->orderBy('id','desc')->first(['rate','create_time','confirm_status']);
        $res = $this->objToArray($res);
        return $res;
    }

    /**
     * 更改或新增公会成员费率值
     *
     * @param [int] $user_id 公会成员id
     * @param [int] $unid 公会id
     * @param [int] $rate 调整费率
     * @return bool
     */
    public function setUserRate($user_id,$unid,$rate)
    {
        $check = DB::table($this->table_union_user_rate)->where(['un_id'=>$unid,'user_id'=>$user_id])->first();
        $check = $this->objToArray($check);
        if(!empty($check))
        {
            $update['rate'] = $rate;//费率值
            $update['confirm_status'] = 0;//更改用户费率时需要用户确认0待确认1已确认
            $update['create_time'] = Carbon::now()->toDateTimeString();
            $status = DB::table($this->table_union_user_rate)->where('id',$check['id'])->update($update);
        }else{
            $insert['un_id'] = $unid;//公会id
            $insert['user_id'] = $user_id;//更改用户id
            $insert['rate'] = $rate;//费率调整
            $insert['confirm_status'] = 0;//0待确认1已确认
            $insert['create_time'] = Carbon::now()->toDateTimeString();
            $status = DB::table($this->table_union_user_rate)->insert($insert);
        }
        return $status;
    }

    /*
     * 获取用户对已认证公会ID
     * */
    public function getSettleUnionUserIdByUserId($userId)
    {
        if(empty($userId)) {
            return 0;
        }
        $unionUser = DB::table($this->user_table)
            ->where('user_id', $userId)
            ->first();
        $unionUser = $this->objToArray($unionUser);
        if(empty($unionUser) || empty($unionUser['un_id'])) {
            return 0;
        }

        $union = DB::table($this->union_table)
            ->where('id', $unionUser['un_id'])
            ->first();
        $union = $this->objToArray($union);
        if(empty($union) || empty($union['id'])) {
            return 0;
        }
        if($union['authentication_status'] > 0) {
            return (int) $union['id'];
        }

        return 0;
    }

    /**
     * 公会成员确认对私分成费率值
     *
     * @param [int] $unid
     * @param [int] $userid
     * @return void
     */
    public function confirmUnionRateByUser($unid,$userid)
    {
        $update['confirm_status'] = 1;//1确认0默认
        $update['update_time'] = Carbon::now()->toDateTimeString();
        $res = DB::table($this->table_union_user_rate)->where(['un_id'=>$unid,'user_id'=>$userid])->update($update);
        return $res;
    }
}
